<template>
  <a-modal
    class="common-modal"
    :title="title"
    :footer="null"
    :width="550"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @cancel="handleCancel"
    :maskClosable="false"
    style="top: 5%"
  >
    <a-spin :spinning="confirmLoading">
      <a-form
        :model="formState"
        @validateFields="handleOk"
        ref="formRef"
        layout="vertical"
        class="common-modal-content"
      >
        <a-row :gutter="24">
          <a-col :span="24">
            <a-form-item
              :label="$t('deviceManage.bridgeRoadNo')"
              name="code"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
            >
              <a-input
                v-model:value.trim="formState.code"
                disabled
                :placeholder="$t('deviceManage.autoGenerate')"
              />
            </a-form-item>
          </a-col>

          <a-col :span="24">
            <a-form-item
              :label="$t('deviceManage.startBridgePoint')"
              name="alineStationId"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              :rules="[
                {
                  required: true,
                  message: $t('deviceManage.startBridgePoint'),
                },
              ]"
            >
              <a-select
                v-model:value.trim="formState.alineStationId"
                show-search
                :filterOption="filterOption"
                :options="birdList"
                @change="handleChange1"
              />
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item
              :label="$t('deviceManage.endBridgePoint')"
              name="blineStationId"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              :rules="[
                {
                  required: true,
                  message: $t('deviceManage.endBridgePoint'),
                },
              ]"
            >
              <a-input-group compact>
                <a-select
                  v-model:value.trim="formState.blineStationId"
                  show-search
                  :filterOption="filterOption"
                  :options="birdList"
                  @change="handleChange2"
                  style="width: 70%"
                />
                <a-button
                  type="primary"
                  @click="getRoadList"
                  style="width: 30%"
                  >{{ $t("other.seePath") }}</a-button
                >
              </a-input-group>
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item
              :label="$t('deviceManage.path')"
              name="direction"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              :rules="[
                { required: true, message: $t('other.pleaseSelectPath') },
              ]"
            >
              <a-select
                v-model:value="formState.direction"
                allowClear
                :placeholder="$t('common.pleaseSelect')"
              >
                <a-select-option
                  v-for="(item, i) in roadList"
                  :value="item.direction"
                  :key="i"
                  >{{ item.direction }}</a-select-option
                >
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item
              :label="$t('common.startState')"
              name="status"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              :rules="[
                { required: true, message: $t('sysManage.selectEnable') },
              ]"
            >
              <a-radio-group v-model:value="formState.status">
                <a-radio
                  v-for="(item, index) in selectOptions.status"
                  :value="item.value"
                  :key="index"
                  >{{ item.label }}</a-radio
                >
              </a-radio-group>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
      <div class="common-modal-footer">
        <a-button @click="handleCancel" class="cancel">{{
          $t("common.cancel")
        }}</a-button>
        <a-button @click="handleOk" type="primary" class="confirm">{{
          $t("common.ok")
        }}</a-button>
      </div>
    </a-spin>
  </a-modal>
</template>

<script setup name="addDialog">
import { nextTick, ref, onBeforeMount } from "vue";
import axios from "@/utils/request";
import { cloneDeep, isEmpty } from "lodash";
import { message } from "ant-design-vue";

import i18n from "@/locales/index";
const { t } = i18n.global;
const emits = defineEmits(['ok'])
const labelCol = { xs: { span: 24 }, sm: { span: 23 } }
const wrapperCol = { xs: { span: 24 }, sm: { span: 23 } }
let title = ref('')
let visible = ref(false)
let isEdit = ref(false)
let confirmLoading = ref(false)
const selectOptions = ref({})
let recordInfo = ref({})
let formState = ref({})
const formRef = ref()
let roadList = ref([])
let birdList = ref([])
let objSelect1 = ref({})
let objSelect2 = ref({})
let fileList = ref([])

const getRoadList = async () => {
  let params = doParam()
  if (!isEmpty(params)){
    confirmLoading.value = true
    const res = await axios.postAction('/api/device/bridge-path/calculate-bridge-path', params)
    confirmLoading.value = false
    if (res.success) {
      if (!isEmpty(res.data)) {
        res.data.forEach((item, index) => {
          let arr2 = [];
          item.bridgePathDetails &&
            item.bridgePathDetails.forEach((i) => {
              arr2.push(
                i.lineNo + "-" + i.masterTrackNo + "-" + i.lineStationNo
              );
            });
          item.direction = arr2.join("->") || "";
          item.indexValue = index + 1;
        });
      }
      roadList.value = res.data
      confirmLoading.value = false
    }
  } else {
    message.warn(t("other.pleaseSelectStartOrEndBridge"));
  }
};
const filterOption = (val, option) => {
  return option.value.toLowerCase().indexOf(val.toLowerCase()) >= 0;
};
//桥接列表
const handleChange1 = async (val, object1) => {
  console.log(val);
  objSelect1.value = object1;
};
const handleChange2 = async (val, object1) => {
  console.log(val);
  objSelect2.value = object1;
};

const edit = async (record, editable) => {
  const res = await axios.getAction('/api/device/hanger-line-bridge/get-all-bridge-station')
  if (res.success){
    if (!isEmpty(res.data)){
      res.data.forEach((i)=>{
        return  i.value = i.lineNo + "-" + i.masterTrackNo + "-"+i.lineStationNo }
      )
    }
    birdList.value = res.data || [];
  }
  console.log(birdList.value,'----------------------')

  initModalData(record, editable)
  await nextTick()
  formRef.value.resetFields()
  console.log(record)
  //设置桥接默认选中
  if (!record.id) {
    // record.bridgeType = 0;
    record.status = 0;
  }
  formState.value = cloneDeep(record)
  console.log(formState)
}

const initModalData = (record, editable) => {
  title.value = t("other.addBridge");
  recordInfo.value = Object.assign({}, record);
  visible.value = true;
  isEdit.value = editable;
};

const handleOk = async () => {
  try {
    const values = await formRef.value.validateFields();
    // console.log('提交表单:::', values)
    if (!isEmpty(roadList.value)){
      let obj = roadList.value.filter(i=>i.direction == values.direction)
      if (!isEmpty(obj)){
        let params = cloneDeep(obj[0])
        let obj1 = doParam()
        if (!isEmpty(obj1)){
          obj1.bridgePathDetails = params.bridgePathDetails  || []
          obj1.status = formState.value.status
          const res = await axios.postAction('/api/device/bridge-path/save', obj1)
          // console.log("提交表单success返回数据", res)
          if (res.success) {
            emits("ok");
            confirmLoading.value = false;
            visible.value = false;
            initModalStatus();
            message.success(this.$t("common.doSuccess"));
          }
        }
      } else {
        message.error(t("other.startAndEndBridgeNull"));
      }
    } else {
      message.error(t("other.pathNotFound"));
    }
  } catch (err) {
    console.log("0000000", err);
  }
  confirmLoading.value = false;
};

// 处理参数
const doParam = () => {
  let params = {};
  if (!isEmpty(objSelect1.value) && !isEmpty(objSelect2.value)) {
    const objStart = cloneDeep(objSelect1.value);
    const objEnd = cloneDeep(objSelect2.value);
    params.startLineId = objStart.lineId;
    params.startMasterTrackId = objStart.masterTrackId;
    params.startLineStationId = objStart.lineStationId;
    params.endLineId = objEnd.lineId;
    params.endMasterTrackId = objEnd.masterTrackId;
    params.endLineStationId = objEnd.lineStationId;
  }
  return params;
};
const handleCancel = () => {
  visible.value = false;
  initModalStatus();
};

const initModalStatus = () => {
  confirmLoading.value = false;
  formState.value = {};
  formRef.value.resetFields();
  fileList.value = [];
  objSelect1.value = {};
  objSelect2.value = {};
  roadList.value = [];
  birdList.value = [];
};
const initSelectOptions = (obj) => {
  console.log(obj)
  selectOptions.value = obj
}
onBeforeMount(async () => {
  // console.log("editDialog");
});
defineExpose({
  edit,
  initSelectOptions,
});
</script>
